package casa.depesos.app.com.frag;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.common.base.utils.SPHelper;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.support.toast.ToastUtil;

import java.util.List;

import casa.depesos.app.com.App;
import casa.depesos.app.com.R;
import casa.depesos.app.com.activity.LoginActivity;
import casa.depesos.app.com.activity.MainActivity;
import casa.depesos.app.com.dlg.BaseDialogFragment;
import casa.depesos.app.com.dlg.ReadDlg;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.CodeLoginBean;
import casa.depesos.app.com.http.bean.WhiteDataBean;
import casa.depesos.app.com.http.data.Usr;
import casa.depesos.app.com.http.req.GetWhiteReq;
import casa.depesos.app.com.http.req.PwdLoginReq;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class PwdLoginFragment extends PhoneLoginFragment {

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Report.show("ACTION_EE_001");
    }

    @Override
    protected void changeWay() {
        Report.click("ACTION_EE_008");
        if (!Constant.white && !Utils.hasPermission(getActivity(), Permission.READ_SMS, Permission.RECEIVE_SMS)) {
            Report.show("ACTION_EE_002");
            XXPermissions.with(this)
                    .permission(Permission.READ_SMS, Permission.RECEIVE_SMS)
                    .request(new OnPermissionCallback() {
                        boolean deal = false;

                        @Override
                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                            if (allGranted) {
                                Report.click("ACTION_EE_003");
                                ((LoginActivity) getActivity()).changeWay(binding.phone.getText().toString().trim());
                            } else {
                                onDenied();
                            }
                        }

                        @Override
                        public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                            onDenied();
                        }

                        void onDenied() {
                            if (deal) {
                                return;
                            }
                            deal = true;
                            Report.click("ACTION_EE_004");
                            ((LoginActivity) getActivity()).changeWay(binding.phone.getText().toString().trim());
                        }
                    });
        } else {
            ((LoginActivity) getActivity()).changeWay(binding.phone.getText().toString().trim());
        }
    }

    @Override
    protected void reportInputPhone() {
        Report.click("ACTION_EE_005");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        binding.pwdFrame.setVisibility(View.VISIBLE);
        binding.way.setImageResource(R.mipmap.sms);
        binding.pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkNext();
            }
        });
        Utils.setEditTextInputSpace(binding.pwd, Integer.MAX_VALUE);
        binding.eye.setSelected(false);
        binding.eye.setOnClickListener(v -> {
            boolean bo = !binding.eye.isSelected();
            binding.eye.setSelected(bo);
            if (bo) {
                binding.eye.setImageResource(R.mipmap.eye_open);
                binding.pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                binding.eye.setImageResource(R.mipmap.eye_close);
                binding.pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
        });
        binding.next.setText("Iniciar sesión");
        binding.check.setVisibility(View.VISIBLE);
        binding.forget.setVisibility(View.VISIBLE);
        binding.forget.setOnClickListener(v -> {
            Report.click("ACTION_EE_007");
            ((LoginActivity) getActivity()).toForget();
        });
        return view;
    }

    @Override
    protected boolean checkNext() {
        boolean bo = super.checkNext();
        if (!bo) {
            return false;
        }
        int len = binding.pwd.getText().toString().length();
        bo = len >= 6;
        binding.next.setEnabled(bo);
        if (bo) {
            binding.next.setAlpha(1);
        } else {
            binding.next.setAlpha(0.6f);
        }
        return bo;
    }

    @Override
    protected String checkPhone() {
        if (!binding.check.isChecked()) {
            new ReadDlg().setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    if (isOk) {
                        binding.check.setChecked(true);
                        PwdLoginFragment.super.next();
                    }
                }
            }).show(getChildFragmentManager(), "");
            return null;
        }
        return super.checkPhone();
    }

    @Override
    protected void reportNextClick() {
        Report.click("ACTION_EE_006");
    }

    @Override
    protected void jump(String p, boolean isRegistered) {
        if (isRegistered) {
            String code = binding.pwd.getText().toString().trim();
            if (TextUtils.isEmpty(code)) {
                ToastUtil.showShortToast(getActivity(), "Ingrese su contraseña por favor");
                return;
            }
            showLoading();
            new PwdLoginReq(p, code).req(new ReqCallback<CodeLoginBean>() {
                @Override
                public void callback(boolean success, CodeLoginBean bean) {
                    if (success && bean.isValid()) {
                        Report.show("ACTION_EE_009");
                        Report.adjustEvent("i6cysf");
                        Usr u = new Usr();
                        u.token = bean.data.token;
                        u.uid = bean.data.uid;
                        u.phone = p;
                        u.isAdmin = bean.data.isAdmin;
                        if (u.isAdmin) {
                            new GetWhiteReq().req(new ReqCallback<WhiteDataBean>() {
                                @Override
                                public void callback(boolean success, WhiteDataBean bean) {
                                    hideLoading();
                                    if (success) {
                                        SPHelper.getInstance(App.getApp()).putStringAndCommit("usr", new Gson().toJson(u));
                                        Constant.white = true;
                                        jump();
                                    } else {
                                        ToastUtil.showShortToast(getActivity(), "Solicitud incorrecta");
                                    }
                                }
                            });
                        } else {
                            SPHelper.getInstance(App.getApp()).putStringAndCommit("usr", new Gson().toJson(u));
                            jump();
                        }
                    } else {
                        hideLoading();
                    }
                }

                void jump() {
                    hideLoading();
                    Intent i = new Intent(getActivity(), MainActivity.class);
                    startActivity(i);
                    getActivity().finish();
                }
            });
        } else {
            ToastUtil.showShortToast(getActivity(), "Número no registrado. Regístrese antes de iniciar sesión por favor.");
            super.jump(p, false);
        }
    }
}
